<template>
    <div class="box">
        <el-form :model="form" ref="formRef" label-width="80px" style="width: 400px;">
            <el-form-item label="用户类型">
                <el-select v-model="form.type" placeholder="请选择用户类型">
                    <el-option label="管理人员" value="0"></el-option>
                    <el-option label="工作人员" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="form.username" placeholder="账号" auto-complete="username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input type="password" v-model="form.password" placeholder="密码"
                    auto-complete="current-password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleLogin" style="width: 100%;">
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router"; // 引入路由
const form = ref({
    username: "",
    password: "",
    type: "0",
});

const handleLogin = async () => {
    try {
        const response = await axios.post(
            "http://localhost:8000/plates/login",
            {
                type: form.value.type,
            },
            {
                auth: {
                    username: form.value.username,
                    password: form.value.password,
                },
                headers: {
                    "Content-Type": "application/json",
                },
            }
        );

        if (response.status === 200 && response.data.access_token) {
            // 存储令牌和用户信息
            localStorage.setItem("access_token", response.data.access_token);
            localStorage.setItem("user_info", JSON.stringify(response.data.user_info));

            // 跳转首页
            await router.push({ name: "home" });
            window.location.reload();
            ElMessage.success("登录成功");
        } else {
            if (response.status === 401) {
                ElMessage.error("用户名或密码错误");
            } else {
                ElMessage.error("登录失败，状态码：" + response.status);
            }
        }
    } catch (error) {
        console.error("登录请求失败:", error);
        if (error.response?.status === 401) {
            ElMessage.error("用户名或密码错误");
        } else {
            ElMessage.error("登录失败，请重试");
        }
    }
};
</script>

<style scoped>
.box {
    min-height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-form {
    background: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-link {
    cursor: pointer;
}
</style>